<!-- eslint-disable -->
<template>
  <div class="wechat-bot">
    <div class="step-content">
      <!-- 步骤1：微信登录 -->
      <div v-if="stepStore.activeStep === 0" class="login-step">
        <el-card class="login-card">
          <template #header>
            <div class="card-header">
              <h3>登录微信</h3>
              <el-button type="primary" size="small" @click="openDevTools"
                >开发者工具</el-button
              >
            </div>
          </template>
          <div class="login-content">
            <p>点击下方按钮登录微信，将自动为您分配端口并注入转发工具</p>
            <el-alert
              v-if="error"
              :title="error"
              type="error"
              show-icon
              class="error-alert"
            />
            <el-button
              type="primary"
              size="large"
              :loading="isInjecting"
              @click="injectWeChat"
            >
              登录微信
            </el-button>
          </div>
        </el-card>
        <MessageLog class="message-log" />
      </div>

      <!-- 步骤2：配置转发规则 -->
      <div v-else-if="stepStore.activeStep === 1" class="rules-step">
        <TransferRules
          :port="accountStore.currentAccount?.port"
          class="rules-component"
        />
        <MessageLog class="message-log" />
      </div>

      <!-- 步骤3：转发状态监控 -->
      <div v-else-if="stepStore.activeStep === 2" class="monitor-step">
        <el-card class="monitor-card">
          <template #header>
            <h3>消息转发监控</h3>
          </template>
          <div class="monitor-content">
            <p>正在监听消息，符合条件的消息将被自动转发</p>
            <div class="status-info">
              <p>
                <strong>当前状态：</strong>
                <el-tag type="success">正在转发中</el-tag>
              </p>
              <p>
                <strong>监听端口：</strong>
                {{ accountStore.currentAccount?.port || "未知" }}
              </p>
              <p><strong>已转发消息数：</strong> {{ forwardedMessageCount }}</p>
            </div>
          </div>
        </el-card>
        <MessageLog class="message-log" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import { useLogStore } from "../store/logStore";
import { useAccountStore } from "../store/accountStore";
import { useStepStore } from "../store/stepStore";
import MessageLog from "./MessageLog.vue";
import TransferRules from "./TransferRules.vue";
import { wechatApi, messageListener } from "../services/apiService";

// store
const logStore = useLogStore();
const accountStore = useAccountStore();
const stepStore = useStepStore();

// 本地状态
const isInjecting = ref(false);
const error = ref(null);
const forwardedMessageCount = ref(0);

// 注入微信
const injectWeChat = async () => {
  error.value = null;
  isInjecting.value = true;

  try {
    logStore.addMessage("正在准备注入微信...");

    // 查找可用端口
    logStore.addMessage("查找可用端口...");
    let port = 8900;
    let msgPort = 9900; // 消息端口比DLL端口大1000

    // 获取已使用的端口列表
    const usedPorts = accountStore.accounts.map((acc) => acc.port);

    // 查找未使用的端口
    while (usedPorts.includes(port) && port < 9000) {
      port++;
      msgPort = port + 1000;
    }

    if (port >= 9000) {
      throw new Error("无可用端口，请关闭一些微信实例后重试");
    }

    logStore.addMessage(`已分配DLL端口: ${port}, 消息端口: ${msgPort}`);

    // 启动微信并注入
    logStore.addMessage("正在启动微信并注入...");

    // 获取注入工具路径
    const injectToolPath = await window.electronAPI.getInjectToolPath();

    logStore.addMessage(`注入工具路径: ${injectToolPath}`);

    // 检查注入工具是否存在
    try {
      const fileExists = await window.electronAPI.checkFileExists(
        injectToolPath
      );
      if (!fileExists.exists) {
        logStore.addMessage(`警告: 注入工具不存在于指定路径，请确认文件位置`);
        logStore.addMessage(`尝试在以下位置查找注入工具: ${injectToolPath}`);
        throw new Error(`注入工具不存在: ${injectToolPath}`);
      } else {
        logStore.addMessage(`注入工具已找到，准备执行注入命令`);
      }
    } catch (checkError) {
      logStore.addMessage(`检查文件失败: ${checkError.message}`);
    }

    // 创建临时账号
    const tempAccountId = accountStore.addAccount({
      wxid: "pending",
      nickname: "正在登录...",
      port: port,
      msgPort: msgPort,
      status: "logging_in",
    });

    // 设置为当前账号
    accountStore.setCurrentAccount(tempAccountId);

    // 调用注入函数
    const injectResult = await window.electronAPI.injectWeChat({
      injectToolPath: injectToolPath,
      dllPort: port,
      msgPort: msgPort,
    });

    if (!injectResult.success) {
      throw new Error(`注入失败: ${injectResult.error}`);
    }

    logStore.addMessage("注入命令执行成功，等待微信登录...");
    logStore.addMessage("主进程将自动检查登录状态，请稍候...");

    // 注入成功后，主进程会自动检查登录状态并发送 login-status-update 事件
    // 在 onMounted 中已经添加了对该事件的监听
  } catch (err) {
    error.value = `注入失败: ${err.message}`;
    logStore.addMessage(`注入失败: ${err.message}`);
    isInjecting.value = false;

    // 如果有创建临时账号，则删除
    if (
      accountStore.currentAccount &&
      accountStore.currentAccount.status === "logging_in"
    ) {
      accountStore.removeAccount(accountStore.currentAccount.id);
    }
  }
};

// 处理登录状态更新
const handleLoginStatusUpdate = async (status) => {
  try {
    logStore.addMessage(`登录状态更新: ${JSON.stringify(status)}`);

    // 检查是否有端口不匹配的情况
    if (status.reason && status.reason.includes("端口不匹配")) {
      logStore.addMessage("检测到端口不匹配，尝试调整...");

      // 尝试从错误消息中提取实际端口
      const portMatch = status.reason.match(/尝试连接 (\d+)/);
      const actualPort = portMatch ? parseInt(portMatch[1]) : null;

      if (actualPort && accountStore.currentAccount) {
        logStore.addMessage(
          `调整端口: ${accountStore.currentAccount.port} -> ${actualPort}`
        );

        // 更新账号的端口信息
        accountStore.updateAccount(accountStore.currentAccount.id, {
          port: actualPort,
        });

        // 重新设置API端口
        wechatApi.setPort(actualPort);

        // 不要立即返回，继续处理
        logStore.addMessage("端口已调整，继续检查登录状态...");
      }
    }

    // 如果已登录，获取用户信息并进入下一步
    if (status.isLoggedIn) {
      const port = accountStore.currentAccount?.port;
      if (!port) {
        throw new Error("当前账号端口未知");
      }

      // 设置API端口
      wechatApi.setPort(port);

      // 获取用户信息
      try {
        const userInfoResult = await wechatApi.getUserInfo();
        logStore.addMessage(
          `用户信息获取结果: ${JSON.stringify(userInfoResult)}`
        );

        if (userInfoResult.errno === 0 && userInfoResult.data) {
          // 更新账号信息
          accountStore.updateAccount(accountStore.currentAccount.id, {
            wxid: userInfoResult.data.wx_id,
            nickname: userInfoResult.data.nick_name,
            avatar: userInfoResult.data.avatar_url,
            account: userInfoResult.data.wx_account,
            status: "online",
            userInfo: userInfoResult.data,
          });

          logStore.addMessage(
            `微信登录成功！用户: ${userInfoResult.data.nick_name}`
          );

          // 开始监听消息
          await startMessageListener();
        } else {
          // API 返回错误，但登录状态检查显示已登录
          // 使用模拟用户信息
          logStore.addMessage("API获取用户信息失败，使用模拟用户信息");

          // 更新账号信息
          accountStore.updateAccount(accountStore.currentAccount.id, {
            wxid: "api_detected_user",
            nickname: "API检测用户",
            avatar: "",
            account: "api_detected_account",
            status: "online",
            userInfo: {
              wx_id: "api_detected_user",
              nick_name: "API检测用户",
              avatar_url: "",
              wx_account: "api_detected_account",
            },
          });

          logStore.addMessage("微信登录成功！使用模拟用户信息");

          // 开始监听消息
          await startMessageListener();
        }
      } catch (userInfoError) {
        logStore.addMessage(`获取用户信息失败: ${userInfoError.message}`);

        // 使用模拟用户信息
        accountStore.updateAccount(accountStore.currentAccount.id, {
          wxid: "login_detected_user",
          nickname: "登录检测用户",
          avatar: "",
          account: "login_detected_account",
          status: "online",
          userInfo: {
            wx_id: "login_detected_user",
            nick_name: "登录检测用户",
            avatar_url: "",
            wx_account: "login_detected_account",
          },
        });

        logStore.addMessage("微信登录成功！使用模拟用户信息");

        // 开始监听消息
        await startMessageListener();
      }
    } else if (status.count >= status.maxCount) {
      // 检查超时，登录失败
      error.value = "登录超时，请确认微信是否已打开并登录";
      logStore.addMessage("登录超时，请确认微信是否已打开并登录");
      isInjecting.value = false;

      // 如果有创建临时账号，则删除
      if (
        accountStore.currentAccount &&
        accountStore.currentAccount.status === "logging_in"
      ) {
        accountStore.removeAccount(accountStore.currentAccount.id);
      }
    }
  } catch (err) {
    error.value = `处理登录状态更新失败: ${err.message}`;
    logStore.addMessage(`处理登录状态更新失败: ${err.message}`);
    isInjecting.value = false;
  }
};

// 启动消息监听
const startMessageListener = async () => {
  try {
    const msgPort = accountStore.currentAccount?.msgPort;
    if (!msgPort) {
      throw new Error("消息端口未知");
    }

    // 设置消息监听端口
    messageListener.setPort(msgPort);

    // 设置消息回调函数
    messageListener.setMessageCallback((message) => {
      handleMessage(message);
    });

    // 启动消息监听服务
    const listenResult = await messageListener.startServer();

    if (listenResult) {
      logStore.addMessage("开始监听消息...");

      // 只有在成功监听消息后，才前进到下一步
      stepStore.nextStep();
      isInjecting.value = false;
    } else {
      logStore.addMessage(`监听消息失败，请检查端口 ${msgPort} 是否可用`);
      error.value = `监听消息失败，请检查端口 ${msgPort} 是否可用`;
      isInjecting.value = false;
    }
  } catch (listenError) {
    logStore.addMessage(`监听消息失败: ${listenError.message}`);
    error.value = `监听消息失败: ${listenError.message}`;
    isInjecting.value = false;
  }
};

// 处理来自主进程的消息
const handleMessage = (message) => {
  try {
    // 尝试解析消息为 JSON 对象（如果它是字符串）
    let msgObj = message;
    if (typeof message === "string") {
      try {
        msgObj = JSON.parse(message);
      } catch (e) {
        // 如果不是有效的 JSON，保持原样
        msgObj = { type: "text", content: message };
      }
    }

    // 根据消息类型处理
    if (msgObj.type === "chat_message") {
      // 聊天消息
      const { from_user, to_user, content, timestamp } = msgObj;
      logStore.addMessage(
        `收到消息: 从 ${from_user.nickname || from_user.wxid} 到 ${
          to_user.nickname || to_user.wxid
        }: ${content}`
      );

      // 如果是转发的消息，更新计数
      if (msgObj.is_forwarded) {
        forwardedMessageCount.value++;
      }
    } else if (msgObj.type === "system") {
      // 系统消息
      logStore.addMessage(`系统消息: ${msgObj.content}`);
    } else if (msgObj.type === "error") {
      // 错误消息
      logStore.addMessage(`错误: ${msgObj.content}`);
      error.value = msgObj.content;
    } else {
      // 其他类型消息或纯文本
      logStore.addMessage(
        `收到消息: ${
          typeof message === "string" ? message : JSON.stringify(msgObj)
        }`
      );

      // 如果消息内容包含"转发成功"，更新计数
      const msgContent =
        typeof message === "string" ? message : JSON.stringify(msgObj);
      if (msgContent.includes("转发成功")) {
        forwardedMessageCount.value++;
      }
    }
  } catch (err) {
    logStore.addMessage(`处理消息时出错: ${err.message}`);
    console.error("处理消息时出错:", err);
  }
};

// 处理来自主进程的错误
const handleError = (err) => {
  error.value = `发生错误: ${err}`;
  logStore.addMessage(`发生错误: ${err}`);
};

// 打开开发者工具
const openDevTools = () => {
  if (window.electronAPI && window.electronAPI.openDevTools) {
    window.electronAPI.openDevTools();
  } else {
    logStore.addMessage("开发者工具功能不可用");
  }
};

// 组件挂载
onMounted(() => {
  // 从本地存储恢复状态
  const savedState = localStorage.getItem("wx_bot_state");
  if (savedState) {
    try {
      const state = JSON.parse(savedState);
      if (state.step !== undefined) {
        stepStore.setStep(state.step);
      }
    } catch (e) {
      console.error("恢复状态失败", e);
    }
  }

  // 定义事件处理函数
  const messageReceivedHandler = (event) => {
    if (event.detail) {
      handleMessage(event.detail);
    }
  };

  const errorOccurredHandler = (event) => {
    if (event.detail) {
      handleError(event.detail);
    }
  };

  const injectionErrorHandler = (event) => {
    if (event.detail) {
      error.value = `注入错误: ${
        event.detail.error || JSON.stringify(event.detail)
      }`;
      logStore.addMessage(
        `注入错误: ${event.detail.error || JSON.stringify(event.detail)}`
      );
    }
  };

  const injectionOutputHandler = (event) => {
    if (event.detail) {
      logStore.addMessage(
        `注入输出 (${event.detail.type}): ${event.detail.content}`
      );
    }
  };

  // 添加主进程日志处理函数
  const logMessageHandler = (event) => {
    if (event.detail) {
      logStore.addMessage(`[主进程] ${event.detail}`);
    }
  };

  // 添加登录状态更新处理函数
  const loginStatusUpdateHandler = (event) => {
    if (event.detail) {
      handleLoginStatusUpdate(event.detail);
    }
  };

  // 添加端口更新处理函数
  const portUpdateHandler = (event) => {
    if (event.detail) {
      handlePortUpdate(event.detail);
    }
  };

  // 添加事件监听
  window.addEventListener("message-received", messageReceivedHandler);
  window.addEventListener("error_occurred", errorOccurredHandler);
  window.addEventListener("injection-error", injectionErrorHandler);
  window.addEventListener("injection-output", injectionOutputHandler);
  window.addEventListener("log-message", logMessageHandler);
  window.addEventListener("login-status-update", loginStatusUpdateHandler);
  window.addEventListener("port-update", portUpdateHandler);

  // 如果有electronAPI，注册主进程事件监听
  if (window.electronAPI) {
    // 注册端口更新事件监听
    window.electronAPI.onPortUpdate((data) => {
      window.dispatchEvent(new CustomEvent("port-update", { detail: data }));
    });
  }

  // 保存事件处理函数引用，以便在卸载时移除
  window.wxBotEventHandlers = {
    messageReceivedHandler,
    errorOccurredHandler,
    injectionErrorHandler,
    injectionOutputHandler,
    logMessageHandler,
    loginStatusUpdateHandler,
    portUpdateHandler,
  };
});

// 处理端口更新事件
const handlePortUpdate = (data) => {
  try {
    logStore.addMessage(`端口更新: ${JSON.stringify(data)}`);

    if (accountStore.currentAccount && data.actualDllPort) {
      // 如果实际端口与请求的端口不同，更新账号信息
      if (data.actualDllPort !== data.requestedDllPort) {
        logStore.addMessage(
          `更新DLL端口: ${data.requestedDllPort} -> ${data.actualDllPort}`
        );

        // 更新账号的端口信息
        accountStore.updateAccount(accountStore.currentAccount.id, {
          port: data.actualDllPort,
        });

        // 重新设置API端口
        wechatApi.setPort(data.actualDllPort);
      }

      // 如果实际消息端口与请求的端口不同，更新账号信息
      if (data.actualMsgPort && data.actualMsgPort !== data.requestedMsgPort) {
        logStore.addMessage(
          `更新消息端口: ${data.requestedMsgPort} -> ${data.actualMsgPort}`
        );

        // 更新账号的消息端口信息
        accountStore.updateAccount(accountStore.currentAccount.id, {
          msgPort: data.actualMsgPort,
        });
      }
    }
  } catch (err) {
    logStore.addMessage(`处理端口更新失败: ${err.message}`);
  }
};

// 组件卸载前清理
onBeforeUnmount(() => {
  // 保存当前状态到本地存储
  localStorage.setItem(
    "wx_bot_state",
    JSON.stringify({
      step: stepStore.activeStep,
    })
  );

  // 停止消息监听服务
  messageListener.stopServer().catch((err) => {
    console.error("停止消息监听服务失败:", err);
  });

  // 移除事件监听
  if (window.wxBotEventHandlers) {
    window.removeEventListener(
      "message-received",
      window.wxBotEventHandlers.messageReceivedHandler
    );
    window.removeEventListener(
      "error_occurred",
      window.wxBotEventHandlers.errorOccurredHandler
    );
    window.removeEventListener(
      "injection-error",
      window.wxBotEventHandlers.injectionErrorHandler
    );
    window.removeEventListener(
      "injection-output",
      window.wxBotEventHandlers.injectionOutputHandler
    );
    window.removeEventListener(
      "log-message",
      window.wxBotEventHandlers.logMessageHandler
    );
    window.removeEventListener(
      "login-status-update",
      window.wxBotEventHandlers.loginStatusUpdateHandler
    );
    window.removeEventListener(
      "port-update",
      window.wxBotEventHandlers.portUpdateHandler
    );

    // 清除引用
    window.wxBotEventHandlers = null;
  }
});
</script>

<style scoped>
.wechat-bot {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
}

.steps {
  margin-bottom: 30px;
}

.step-content {
  min-height: 500px;
}

.login-step {
  display: flex;
  gap: 20px;
  margin-top: 20px;
  height: 500px;
}

.rules-step,
.monitor-step {
  margin-top: 20px;
  display: flex;
  gap: 20px;
  height: 500px;
}

.login-card {
  flex: 1;
}

.login-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.error-alert {
  margin: 20px 0;
  width: 100%;
}

.message-log {
  width: 350px;
  flex-shrink: 0;
  height: 100%;
}

.status-info {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-top: 20px;
}

.rules-component {
  flex: 1;
  overflow-y: auto;
}

.monitor-card {
  flex: 1;
}

@media (max-width: 768px) {
  .login-step,
  .rules-step,
  .monitor-step {
    flex-direction: column;
    height: auto;
  }

  .message-log {
    width: 100%;
    margin-top: 20px;
    height: 300px;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
